/**
 * Cross-platform configuration path resolver
 * Provides standard configuration file paths for different operating systems
 */

const path = require('path');
const os = require('os');

class ConfigPathResolver {
    constructor() {
        this.platform = os.platform();
        this.homeDir = os.homedir();
        this.appName = 'vision-analyzer';
        this.configFileName = 'settings.json';
    }

    /**
     * Get the standard configuration directory for the current platform
     * @returns {string} Configuration directory path
     */
    getConfigDir() {
        switch (this.platform) {
            case 'win32':
                // Windows: %LOCALAPPDATA%\vision-analyzer\Config
                return path.join(process.env.LOCALAPPDATA || path.join(this.homeDir, 'AppData', 'Local'), this.appName, 'Config');

            case 'darwin':
                // macOS: ~/Library/Preferences/vision-analyzer
                return path.join(this.homeDir, 'Library', 'Preferences', this.appName);

            default: // Linux and other Unix-like systems
                // Linux: ~/.config/vision-analyzer
                return path.join(this.homeDir, '.config', this.appName);
        }
    }

    /**
     * Get the full path to the configuration file
     * @returns {string} Configuration file path
     */
    getConfigFilePath() {
        return path.join(this.getConfigDir(), this.configFileName);
    }

    /**
     * Get the legacy configuration directory (project root)
     * @param {string} projectRoot - Project root directory
     * @returns {string} Legacy configuration directory
     */
    getLegacyConfigDir(projectRoot) {
        return projectRoot;
    }

    /**
     * Get the legacy configuration file path
     * @param {string} projectRoot - Project root directory
     * @returns {string} Legacy configuration file path
     */
    getLegacyConfigFilePath(projectRoot) {
        return path.join(projectRoot, 'config.json');
    }

    /**
     * Get all possible configuration file paths in order of priority
     * @param {string} projectRoot - Project root directory
     * @returns {Array<string>} Array of configuration file paths
     */
    getAllPossiblePaths(projectRoot) {
        const currentWorkingDir = process.cwd();
        return [
            // 1. Current working directory (for development)
            path.join(currentWorkingDir, this.configFileName),

            // 2. Standard platform-specific location
            this.getConfigFilePath(),

            // 3. Legacy project root location (for backward compatibility)
            this.getLegacyConfigFilePath(projectRoot)
        ];
    }

    /**
     * Get the best available configuration file path
     * @param {string} projectRoot - Project root directory
     * @returns {Object} {path: string, source: string} or null if none found
     */
    getBestConfigPath(projectRoot) {
        const fs = require('fs');
        const possiblePaths = this.getAllPossiblePaths(projectRoot);

        for (const configPath of possiblePaths) {
            if (fs.existsSync(configPath)) {
                let source = 'unknown';
                if (configPath.includes(process.cwd())) {
                    source = 'working-directory';
                } else if (configPath === this.getConfigFilePath()) {
                    source = 'standard-platform';
                } else if (configPath === this.getLegacyConfigFilePath(projectRoot)) {
                    source = 'legacy-project-root';
                }

                return { path: configPath, source };
            }
        }

        return null;
    }

    /**
     * Ensure the configuration directory exists
     * @returns {string} Configuration directory path
     */
    ensureConfigDir() {
        const fs = require('fs');
        const configDir = this.getConfigDir();

        if (!fs.existsSync(configDir)) {
            fs.mkdirSync(configDir, { recursive: true });
        }

        return configDir;
    }

    /**
     * Migrate configuration from legacy location to standard location
     * @param {string} projectRoot - Project root directory
     * @returns {Object} Migration result
     */
    migrateFromLegacy(projectRoot) {
        const fs = require('fs');
        const legacyPath = this.getLegacyConfigFilePath(projectRoot);
        const standardPath = this.getConfigFilePath();

        // If standard config already exists, no migration needed
        if (fs.existsSync(standardPath)) {
            return {
                migrated: false,
                reason: 'standard-config-exists',
                legacyPath,
                standardPath
            };
        }

        // If legacy config doesn't exist, nothing to migrate
        if (!fs.existsSync(legacyPath)) {
            return {
                migrated: false,
                reason: 'no-legacy-config',
                legacyPath,
                standardPath
            };
        }

        try {
            // Ensure standard config directory exists
            this.ensureConfigDir();

            // Copy legacy config to standard location
            const legacyContent = fs.readFileSync(legacyPath, 'utf8');
            fs.writeFileSync(standardPath, legacyContent, 'utf8');

            return {
                migrated: true,
                reason: 'successful-migration',
                legacyPath,
                standardPath
            };
        } catch (error) {
            return {
                migrated: false,
                reason: 'migration-failed',
                error: error.message,
                legacyPath,
                standardPath
            };
        }
    }

    /**
     * Get platform information
     * @returns {Object} Platform information
     */
    getPlatformInfo() {
        return {
            platform: this.platform,
            homeDir: this.homeDir,
            configDir: this.getConfigDir(),
            configFilePath: this.getConfigFilePath(),
            appName: this.appName,
            configFileName: this.configFileName
        };
    }
}

module.exports = ConfigPathResolver;